# Create your tasks here
from __future__ import absolute_import, unicode_literals

import os
import shutil

from celery import shared_task
from django.core.exceptions import ObjectDoesNotExist

from XApiTestServer.models import ProjectInfo
from XApiTestServer.utils.test_generator import gen_test_by_project, gen_test_by_module, gen_test_by_suite
from XApiTestServer.utils.test_report import summary_timestamp_to_datetime, add_test_report
from XApiTestServer.utils.emails import send_email_report
from XApiTestServer.utils.common import get_time_stamp

from httprunner.api import HttpRunner, logger


@shared_task
def main_hrun(testset_path, report_name):
    """
    用例运行
    :param testset_path: dict or list
    :param report_name: str
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    runner.run(testset_path)

    shutil.rmtree(testset_path)

    runner.summary = summary_timestamp_to_datetime(runner.summary)
    report_path = add_test_report(runner, report_name=report_name)
    os.remove(report_path)


@shared_task
def project_hrun(*args, **kwargs):
    """
    异步运行整个项目
    :param env_name: str: 环境地址
    :param project: str
    :return:
    """
    logger.setup_logger('INFO')

    project_id = kwargs["index"]
    config_id = kwargs["cfg_id"]
    receiver = kwargs["receiver"]

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    id = ProjectInfo.objects.get(project_name=project).id

    test_base_path = os.path.join(os.getcwd(), "suite")
    test_base_path = os.path.join(test_base_path, get_time_stamp())

    gen_test_by_project(project_id, test_base_path, config_id)

    runner.run(test_base_path)
    shutil.rmtree(test_base_path)

    runner.summary = summary_timestamp_to_datetime(runner.summary)
    report_path = add_test_report(runner, report_name=name)

    if receiver != '':
        send_email_report(receiver, report_path)
    os.remove(report_path)


@shared_task
def module_hrun(*args, **kwargs):
    """
    异步运行模块
    :param env_name: str: 环境地址
    :param project: str：项目所属模块
    :param module: str：模块名称
    :return:
    """
    logger.setup_logger('INFO')

    module_id = kwargs["index"]
    config_id = kwargs["cfg_id"]
    receiver = kwargs["receiver"]

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    test_base_path = os.path.join(os.getcwd(), "suite")
    test_base_path = os.path.join(test_base_path, get_time_stamp())

    try:
        for module_id in args:
            gen_test_by_module(module_id, test_base_path, config_id)
    except ObjectDoesNotExist:
        return '找不到模块信息'

    runner.run(test_base_path)

    shutil.rmtree(test_base_path)
    runner.summary = summary_timestamp_to_datetime(runner.summary)
    report_path = add_test_report(runner, report_name=name)

    if receiver != '':
        send_email_report(receiver, report_path)
    os.remove(report_path)


@shared_task
def suite_hrun(*args, **kwargs):
    """
    异步运行套件
    :param env_name: str: 环境地址
    :param project: str：项目所属模块
    :param module: str：模块名称
    :return:
    """
    logger.setup_logger('INFO')

    suite_id = kwargs["index"]
    config_id = kwargs["cfg_id"]
    receiver = kwargs["receiver"]

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    test_base_path = os.path.join(os.getcwd(), "suite")
    test_base_path = os.path.join(test_base_path, get_time_stamp())

    try:
        gen_test_by_suite(suite_id, test_base_path, config_id)
    except ObjectDoesNotExist:
        return '找不到Suite信息'

    runner.run(test_base_path)

    shutil.rmtree(test_base_path)

    runner.summary = summary_timestamp_to_datetime(runner.summary)
    report_path = add_test_report(runner, report_name=name)

    if receiver != '':
        send_email_report(receiver, report_path)
    os.remove(report_path)
